package com.ukit.weather_xml

import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.view.ActionMode
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.squareup.picasso.MemoryPolicy
import com.squareup.picasso.Picasso
import com.ukit.weather_xml.Other.DataManger.Settings
import com.ukit.weather_xml.Other.DataManger.SettingsApp
import com.ukit.weather_xml.Other.DataManger.WeatherDao
import com.ukit.weather_xml.Other.DataManger.WeatherDatabase
import com.ukit.weather_xml.databinding.ActivityMainBinding
import com.ukit.weather_xml.weather.WeatherConnector
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Locale
import com.ukit.weather_xml.Other.DataManger.SettingsDao

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private lateinit var weather: WeatherConnector


    @OptIn(DelicateCoroutinesApi::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val database = WeatherDatabase.getDatabase(applicationContext)
        SettingsApp.weatherDao = database.weatherDao()
        SettingsApp.settingsDao = database.settingsDao()

        GlobalScope.launch(Dispatchers.Main) {
            val settings = SettingsApp.settingsDao.getSettings()

            if (!settings.isNullOrEmpty()) {
                val city = settings[0].city ?: "Москва"
                weather = WeatherConnector(city)
                binding.changeCity.text = city
                refreshData()
            } else {
                val defaultCity = "Москва"
                weather = WeatherConnector(defaultCity)
                binding.changeCity.text = defaultCity
                SettingsApp.settingsDao.insertSettings(Settings(city = defaultCity))
                refreshData()
            }
        }

        binding.main.setOnRefreshListener {
            GlobalScope.launch(Dispatchers.Main) {
                refreshData()
            }
        }

        binding.changeCity.setOnClickListener {
            startActivity(ChangeCityActivity.newIntent(this@MainActivity))
        }
    }

    override fun onResume() {
        super.onResume()
        if (::weather.isInitialized) {
            GlobalScope.launch(Dispatchers.Main) {
                refreshData()
                SettingsApp.settingsDao.getSettings()!!.forEach{
                    Log.e("ФФФ", it.city)
                }
                binding.changeCity.text = SettingsApp.settingsDao.getSettings()?.get(0)?.city ?: "Москва"
            }
        }
    }

    @OptIn(DelicateCoroutinesApi::class)
    @SuppressLint("SetTextI18n")
    private suspend fun refreshData() {
        val weatherData = weather.getWeather()
        withContext(Dispatchers.IO) {
            SettingsApp.weatherDao.insertWeatherData(
                com.ukit.weather_xml.Other.DataManger.WeatherData(
                    city = weatherData.location.name,
                    temperature = weatherData.current.temp_c,
                    humidity = weatherData.current.humidity,
                    windSpeed = weatherData.current.wind_mph,
                    timestamp = System.currentTimeMillis()
                )
            )
        }
        GlobalScope.launch(Dispatchers.Main) {
            val weather = weather.getWeather()

            //Temperature block
            binding.temperature.text = "${weather.current.temp_c.toInt()}°"
            binding.minMax.text = "Макс: ${weather.forecast[0].date_epoch.maxtemp_c}°, Мин: ${weather.forecast[0].date_epoch.mintemp_c}°"

            loadImage(weather.current.condition.icon, binding.imageView2)

            //Time first
            binding.timeOneTemp.text = "${weather.forecast[0].hour[3].temp_c}°"
            binding.timeOne.text = weather.forecast[0].hour[6].time.split(" ")[1]
            loadImage(weather.forecast[0].hour[6].condition.icon, binding.timeOneImg)

            //Time second
            binding.timeSecondTemp.text = "${weather.forecast[0].hour[12].temp_c}°"
            binding.timeSecond.text = weather.forecast[0].hour[12].time.split(" ")[1]
            loadImage(weather.forecast[0].hour[12].condition.icon, binding.timeSecondImg)

            //Time third
            binding.timeThirdTemp.text = "${weather.forecast[0].hour[18].temp_c}°"
            binding.timeThird.text = weather.forecast[0].hour[18].time.split(" ")[1]
            loadImage(weather.forecast[0].hour[18].condition.icon, binding.timeThirdImg)

            binding.humidity.text = "Влажность: ${weather.current.humidity}"
            binding.windSpeed.text = String.format("Скорость ветра: %.2f м/с", weather.current.wind_mph)
            binding.main.isRefreshing = false
        }
        val currentDate = LocalDate.now()
        val formatter = DateTimeFormatter.ofPattern("d MMMM", Locale("ru"))
        val formattedDate = formatter.format(currentDate)
        binding.dateToday.text = formattedDate
    }

    private fun loadImage(url: String, target: ImageView) {
        Picasso.get()
            .load(formatUrl(url))
            .memoryPolicy(MemoryPolicy.NO_CACHE)
            .into(target)
    }

    private fun formatUrl(url: String): String {
        return if (url.startsWith("http://") || url.startsWith("https://")) {
            url
        } else {
            "https://$url"
        }
    }

    suspend fun changeCity(newCity: String) {
        weather.setCity(newCity.trim())
        SettingsApp.settingsDao.insertSettings(Settings(city = newCity))
        binding.changeCity.text = newCity
        refreshData()
    }
}